using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;

using System.Data;
using Prodma.DataAccess.Database;
using Prodma.DataAccess.Models.ViewModels;
using Prodma.DataAccess.DataService;
using Prodma.DataAccess.DataService.ListService;
using Prodma.DataAccess.Helper.Enumerators;
using Prodma.DataAccess.Authorization;
using Prodma.DataAccess.Repositories;
using System.Configuration;
using System.IO;

namespace Prodma.Panel.Controllers
{
    [Authorize]
    public class GalleryCategoryController : Controller
    {

        #region Repository Setters

        private IGalleryCategoryRepository repository;

        public GalleryCategoryController() : this(new GalleryCategoryService()) { }

        public GalleryCategoryController(IGalleryCategoryRepository _repository)
        {
            repository = _repository;
        }

        #endregion


        #region Index
        [NavigationFilter(MenuAdmins.GalleryManagement, AuthorizationType.Read)]
        public ActionResult Index()
        {
            int page = 0;
            if (Request.QueryString["page"] != "" && Request.QueryString["page"] != null)
            {
                page = Convert.ToInt32(Request.QueryString["page"]);
            }

            if (Request.QueryString["find"] != "" && Request.QueryString["find"] != null)
            {
                Dictionary<string, string> find = new Dictionary<string, string>();
                find.Add("name", Request.QueryString["find"]);
                ViewData["totalRowCount"] = repository.GetTotalRowCount(find);
                return View(repository.GetList(page, find));
            }
            else
            {
                ViewData["totalRowCount"] = repository.GetTotalRowCount();
                return View(repository.GetList(page));
            }
        }
        #endregion


        #region New
        [NavigationFilter(MenuAdmins.GalleryManagement, AuthorizationType.Write)]
        public ActionResult New()
        {
            ViewData["areaList"] = AreaList.GetList();
            ViewData["stateList"] = StateList.GetList(StateType.General);

            System.Web.HttpContext.Current.Session["galleryImage"] = null;

            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [NavigationFilter(MenuAdmins.GalleryManagement, AuthorizationType.Write)]
        public ActionResult New(FormCollection form)
        {
            ViewData["areaList"] = AreaList.GetList();
            ViewData["stateList"] = StateList.GetList(StateType.General);

            tb_GalleryCategory category = new tb_GalleryCategory();
            category.Name = Request.Form["name"];
            category.Description = Request.Form["description"];
            string image = ConfigurationManager.AppSettings["galleryBlankImage"].ToString();
            if (System.Web.HttpContext.Current.Session["galleryImage"] != null)
            {
                image = System.Web.HttpContext.Current.Session["galleryImage"].ToString();
            }
            category.Image = image;
            category.Folder = Request.Form["folder"];
            category.tb_AreaReference.EntityKey = new EntityKey("DataContext.tb_Area", "Id", Convert.ToInt32(Request.Form["ddlArea"]));
            category.tb_StateReference.EntityKey = new EntityKey("DataContext.tb_State", "Id", Convert.ToInt32(Request.Form["ddlState"]));

            repository.New(category);

            #region Create Folder

            string defaultPath = ConfigurationManager.AppSettings["galleryImagePath"];
            Directory.CreateDirectory(Server.MapPath(defaultPath) + category.Folder);

            #endregion

            return View();
        }
        #endregion


        #region Edit
        [NavigationFilter(MenuAdmins.GalleryManagement, AuthorizationType.Update)]
        public ActionResult Edit()
        {
            int id = Convert.ToInt32(Request.QueryString["id"]);

            GalleryCategoryVm category = repository.Edit(id);
            ViewData["areaList"] = AreaList.GetList(category.Area.Id);
            ViewData["stateList"] = StateList.GetList(StateType.General, category.State.Id);

            System.Web.HttpContext.Current.Session["galleryImage"] = category.Image;

            return View(category);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [NavigationFilter(MenuAdmins.GalleryManagement, AuthorizationType.Update)]
        public ActionResult Edit(FormCollection form)
        {
            tb_GalleryCategory category = new tb_GalleryCategory();
            category.Name = Request.Form["name"];
            category.Description = Request.Form["description"];
            string image = ConfigurationManager.AppSettings["galleryBlankImage"].ToString();
            if (System.Web.HttpContext.Current.Session["galleryImage"] != null)
            {
                image = System.Web.HttpContext.Current.Session["galleryImage"].ToString();
            }
            category.Image = image;
            category.Folder = Request.Form["folder"];
            category.tb_AreaReference.EntityKey = new EntityKey("DataContext.tb_Area", "Id", Convert.ToInt32(Request.Form["ddlArea"]));
            category.tb_StateReference.EntityKey = new EntityKey("DataContext.tb_State", "Id", Convert.ToInt32(Request.Form["ddlState"]));

            int id = Convert.ToInt32(Request.Form["id"]);
            int page = 0;
            if (Request.QueryString["page"] != "" && Request.QueryString["page"] != null)
            {
                page = Convert.ToInt32(Request.QueryString["page"]);
            }
            repository.Update(id, category);

            #region Update Folder

            string defaultPath = ConfigurationManager.AppSettings["galleryImagePath"];
            string currentFolder = Server.MapPath(defaultPath) + Request.Form["hdnFolder"];
            string destinationFolder = Server.MapPath(defaultPath) + category.Folder;

            if (!Directory.Exists(currentFolder))
            {
                Directory.CreateDirectory(destinationFolder);
            }
            else
            {
                if (currentFolder != destinationFolder)
                {
                    Directory.Move(currentFolder, destinationFolder);
                }
            }

            #endregion

            return RedirectToAction("edit/?id=" + id + "&page=" + page);
        }
        #endregion


        #region Delete
        [NavigationFilter(MenuAdmins.GalleryManagement, AuthorizationType.Delete)]
        public ActionResult Delete()
        {
            string[] idList = Request.QueryString["idList"].Split(',');

            foreach (string id in idList)
            {
                string deleteId = id.Substring(3, id.Length - 3);
                repository.Delete(Convert.ToInt32(deleteId));
            }

            return RedirectToAction("index");
        }
        #endregion


        #region Set Active && Passive
        [NavigationFilter(MenuAdmins.GalleryManagement, AuthorizationType.Update)]
        public ActionResult SetActive()
        {
            string[] idList = Request.QueryString["idList"].Split(',');

            foreach (string id in idList)
            {
                string currentId = id.Substring(3, id.Length - 3);
                repository.SetActive(Convert.ToInt32(currentId));
            }

            return RedirectToAction("index");
        }
        [NavigationFilter(MenuAdmins.GalleryManagement, AuthorizationType.Update)]
        public ActionResult SetPassive()
        {
            string[] idList = Request.QueryString["idList"].Split(',');

            foreach (string id in idList)
            {
                string currentId = id.Substring(3, id.Length - 3);
                repository.SetPassive(Convert.ToInt32(currentId));
            }

            return RedirectToAction("index");
        }
        #endregion


        #region Gallery Category Image Operations

        public ActionResult Image()
        {
            return View();
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        [NavigationFilter(MenuAdmins.GalleryManagement, AuthorizationType.Write)]
        public ActionResult UploadImage()
        {
            foreach (string inputTagName in Request.Files)
            {
                HttpPostedFileBase file = Request.Files[inputTagName] as HttpPostedFileBase;
                string[] fileNames = file.FileName.Split('\\');
                string fileName = fileNames[fileNames.Length - 1];

                if (file.ContentLength > 0)
                {
                    string filePath = filePath = Path.Combine(
                        Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["galleryImagePath"].ToString()),
                        Path.GetFileName(file.FileName));
                    file.SaveAs(filePath);
                    System.Web.HttpContext.Current.Session["galleryImage"] = fileName;
                }
            }

            return RedirectToAction("image", "galleryCategory");
        }

        [NavigationFilter(MenuAdmins.GalleryManagement, AuthorizationType.Delete)]
        public ActionResult RemoveImage()
        {
            int id;
            if (Request.QueryString["id"] != "" && Request.QueryString["id"] != null)
            {
                id = Convert.ToInt32(Request.QueryString["id"]);
            }
            else
            {
                return RedirectToAction("image", "galleryCategory");
            }

            System.Web.HttpContext.Current.Session["galleryImage"] = ConfigurationManager.AppSettings["galleryBlankImage"].ToString();
            repository.RemoveImage(id);

            return RedirectToAction("image", "galleryCategory");
        }

        #endregion

    }
}
